<template>
    <div class="content-container">
        <!-- 添加空白区域，使内容向下移但不要太多 -->
        <div class="admin-page-spacer"></div>
        
        <el-card shadow="never" :body-style="{ padding: '20px' }">
            <el-form :model="form" label-width="160px" :rules="rules">
                <el-form-item label="博客名称" prop="name">
                    <el-input v-model="form.name" clearable />
                </el-form-item>
                <el-form-item label="作者名" prop="author">
                    <el-input v-model="form.author" clearable />
                </el-form-item>
                <el-form-item label="作者头像" prop="avatar">
                    <el-upload class="avatar-uploader" action="#" :on-change="handleTitleImageChange" :auto-upload="false"
                        :show-file-list="false" :on-success="handleAvatarSuccess">
                        <img v-if="form.avatar" :src="form.avatar" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                    <!-- 显示当前头像URL，方便调试 -->
                    <div class="mt-1 text-xs text-gray-400" v-if="form.avatar">
                        当前头像URL: {{ form.avatar }}
                    </div>
                </el-form-item>
                <el-form-item label="介绍语">
                    <el-input v-model="form.introduction" type="textarea" />
                </el-form-item>
                <el-form-item label="开启 GihHub 访问">
                    <el-switch v-model="isGithubCheck" inline-prompt :active-icon="Check" :inactive-icon="Close" @change="githubSwitchChange"/>
                </el-form-item>
                <el-form-item label="GitHub 主页访问地址" v-if="isGithubCheck">
                    <el-input v-model="form.githubHomepage" clearable placeholder="请输入 GitHub 主页访问的 URL" />
                </el-form-item>
                <el-form-item label="开启 CSDN 访问">
                    <el-switch v-model="isCSDNCheck" inline-prompt :active-icon="Check" :inactive-icon="Close" @change="csdnSwitchChange"/>
                </el-form-item>
                <el-form-item label="CSDN 主页访问地址" v-if="isCSDNCheck">
                    <el-input v-model="form.csdnHomepage" clearable placeholder="请输入 CSDN 主页访问的 URL" />
                </el-form-item>
                <el-form-item label="开启 Gitee 访问">
                    <el-switch v-model="isGiteeCheck" inline-prompt :active-icon="Check" :inactive-icon="Close" @change="giteeSwitchChange"/>
                </el-form-item>
                <el-form-item label="Gitee 主页访问地址" v-if="isGiteeCheck">
                    <el-input v-model="form.giteeHomepage" clearable placeholder="请输入 Gitee 主页访问的 URL" />
                </el-form-item>
                <el-form-item label="开启知乎访问">
                    <el-switch v-model="isZhihuCheck" inline-prompt :active-icon="Check" :inactive-icon="Close" @change="zhihuSwitchChange"/>
                </el-form-item>
                <el-form-item label="知乎主页访问地址" v-if="isZhihuCheck">
                    <el-input v-model="form.zhihuHomepage" clearable placeholder="请输入知乎主页访问的 URL" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onSubmit">保存</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { Check, Close } from '@element-plus/icons-vue'
import { uploadFile } from '@/api/admin/file'
import { showMessage } from '@/composables/util'
import { getBlogSettingDetail, updateBlogSetting } from '@/api/admin/blogsetting'
import store from '@/store'

const isGithubCheck = ref(false)
const isCSDNCheck = ref(false)
const isGiteeCheck = ref(false)
const isZhihuCheck = ref(false)


const form = reactive({
    name: '',
    author: '',
    avatar: '',
    introduction: '',
    githubHomepage: '',
    giteeHomepage: '',
    csdnHomepage: '',
    zhihuHomepage: '',
})

const rules = {
    name: [{ required: true, message: '请输入博客名称', trigger: 'blur' }],
    author: [{ required: true, message: '请输入作者名称', trigger: 'blur' }],
    avatar: [{ required: true, message: '请选择作者头像', trigger: 'blur' }],
}

const githubSwitchChange = (e) => {
    if (e == false) {
        form.githubHomepage = ''
    }
}

const csdnSwitchChange = (e) => {
    if (e == false) {
        form.csdnHomepage = ''
    }
}

const giteeSwitchChange = (e) => {
    if (e == false) {
        form.giteeHomepage = ''
    }
}

const zhihuSwitchChange = (e) => {
    if (e == false) {
        form.zhihuHomepage = ''
    }
}

const handleTitleImageChange = (file) => {
    console.log('开始上传文件', file)
    if (!file || !file.raw) {
        showMessage('请选择有效的图片文件', 'error')
        return
    }
    
    let formData = new FormData()
    formData.append("file", file.raw);
    
    // 查看 FormData 内容
    for (let pair of formData.entries()) {
        console.log('FormData 内容:', pair[0], pair[1]);
    }
    
    uploadFile(formData).then((res) => {
        console.log('上传文件完整响应:', JSON.stringify(res))
        
        if (!res || res.success === false) {
            let message = res ? res.message : '上传失败，未知错误'
            showMessage(message, 'error')
            return
        }
        
        // 根据响应格式处理
        let avatarUrl = null
        if (typeof res.data === 'string') {
            // 直接返回URL字符串
            avatarUrl = res.data
        } else if (res.data && typeof res.data.url === 'string') {
            // 返回对象中包含url字段
            avatarUrl = res.data.url
        } else {
            console.error('未能从响应中获取URL:', res)
            showMessage('上传成功，但获取图片地址失败', 'warning')
            return
        }
        
        // 显式地设置表单的avatar字段
        console.log('设置头像URL:', avatarUrl)
        form.avatar = avatarUrl
        
        // 强制更新表单数据
        Object.assign(form, { ...form, avatar: avatarUrl })
        
        showMessage('头像上传成功', 'success')
    }).catch(err => {
        console.error('上传文件错误:', err)
        showMessage('头像上传失败', 'error')
    })
}

function initBlogSetting() {
    console.log('开始获取博客设置...');
    
    getBlogSettingDetail().then((response) => {
        console.log('获取博客设置完整响应:', JSON.stringify(response));
        
        if (response && response.success === true && response.data) {
            // 正常处理响应数据
            form.name = response.data.name || '';
            form.author = response.data.author || '';
            form.avatar = response.data.avatar || '';
            console.log('初始化头像URL:', form.avatar);
            form.introduction = response.data.introduction || '';
            
            // 社交媒体链接
            if (response.data.githubHomepage) {
                isGithubCheck.value = true;
                form.githubHomepage = response.data.githubHomepage;
            }
            if (response.data.giteeHomepage) {
                isGiteeCheck.value = true;
                form.giteeHomepage = response.data.giteeHomepage;
            }
            if (response.data.csdnHomepage) {
                isCSDNCheck.value = true;
                form.csdnHomepage = response.data.csdnHomepage;
            }
            if (response.data.zhihuHomepage) {
                isZhihuCheck.value = true;
                form.zhihuHomepage = response.data.zhihuHomepage;
            }
            
            showMessage('获取博客设置成功', 'success');
        } else {
            // 响应格式不正确
            console.error('响应格式不正确:', response);
            let errorMsg = response && response.message ? response.message : '获取博客设置失败，响应格式不正确';
            showMessage(errorMsg, 'error');
        }
    }).catch((error) => {
        // 网络错误或服务器错误
        console.error('获取博客设置错误:', error);
        
        let errorMsg = '获取博客设置失败: ';
        if (error.response) {
            // 服务器返回了错误状态码
            errorMsg += `服务器返回错误 (${error.response.status})`;
            if (error.response.data && error.response.data.message) {
                errorMsg += ` - ${error.response.data.message}`;
            }
        } else if (error.request) {
            // 请求已发送但没有收到响应
            errorMsg += '服务器未响应，请检查网络连接';
        } else {
            // 请求设置触发错误
            errorMsg += error.message || '未知错误';
        }
        
        showMessage(errorMsg, 'error');
    });
}
initBlogSetting()


const onSubmit = () => {
    // 确保表单数据完整
    console.log('提交的完整表单数据:', JSON.stringify(form))
    
    // 检查必填字段
    if (!form.name) {
        showMessage('请输入博客名称', 'warning')
        return
    }
    
    if (!form.author) {
        showMessage('请输入作者名称', 'warning')
        return
    }
    
    // 检查头像是否存在
    if (!form.avatar) {
        showMessage('请上传头像', 'warning')
        return
    }
    
    console.log('头像URL在提交前:', form.avatar)
    
    // 创建一个新对象，确保数据格式正确
    const submitData = {
        name: form.name,
        author: form.author,
        avatar: form.avatar, // 确保这里拿到的是已上传后的URL
        introduction: form.introduction || '',
        githubHomepage: form.githubHomepage || '',
        csdnHomepage: form.csdnHomepage || '',
        giteeHomepage: form.giteeHomepage || '',
        zhihuHomepage: form.zhihuHomepage || ''
    }
    
    console.log('最终提交数据:', JSON.stringify(submitData))
    
    // 直接使用axios发送请求，避免可能的封装问题
    import('@/axios').then(({ default: axios }) => {
        axios.post("/admin/blog/setting/update", submitData)
            .then(response => {
                console.log('原始更新响应:', response)
                
                if (response.success === true) {
                    showMessage('更新成功', 'success')
                    // 刷新本地数据
                    initBlogSetting()
                    // 同时刷新全局状态
                    store.dispatch('getAdminInfo')
                    store.dispatch('getBlogSetting')
                } else {
                    let message = response.message || '更新失败'
                    showMessage(message, 'warning')
                }
            })
            .catch(error => {
                console.error('更新请求错误:', error)
                showMessage('更新失败，请检查网络或服务器状态', 'error')
            })
    })
}
</script>

<style scoped>
.content-container {
    margin-top: 15px;
}
</style>